import {listFunction, addFunction, updateFunction, removeFunction} from "_api/system/function";
import {_Promise} from "_libs/util";
import Vue from "vue";

export default {
  namespaced: true,
  state: {
    functionList: []
  },
  mutations: {
    setFunctionList(state, functionList) {
      state.functionList = functionList.filter(func => {
        func.moduleName = func.module.name
        return func;
      })
    },
    addFunction(state, func) {
      func.moduleName = func.module.name
      state.functionList.unshift(func)
    },
    updateFunction(state, func) {
      func.moduleName = func.module.name
      state.functionList.forEach(existsFunc => {
        if (existsFunc.id === func.id) {
          let keys = Object.keys(existsFunc);
          keys.forEach(key => {
            Vue.set(existsFunc, key, func[key])
          })
        }
      })
    },
    removeFunction(state, functionId) {
      let functionList = state.functionList;
      functionList.forEach((func, index) => {
        if (func.id === functionId) {
          functionList.splice(index, 1)
        }
      })
    }
  },
  actions: {
    // 获取所有功能
    listFunction({state, commit}) {
      return _Promise(listFunction(), res => {
        commit('setFunctionList', res.data)
      })
    },

    // 添加功能
    addFunction({state, commit}, funtionForm) {
      return _Promise(addFunction(funtionForm), res => {
        commit('addFunction', res.data);
      })
    },

    // 更新功能
    updateFunction({state, commit}, functionForm) {
      return _Promise(updateFunction(functionForm), res => {
        commit('updateFunction', res.data)
      })
    },

    // 删除功能
    removeFunction({state, commit}, func) {
      return _Promise(removeFunction(func.id), res => {
        commit('removeFunction', func.id)
      })
    }
  }
}
